package com.zerui.manager.icc.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.icc.exception.ClientException;
import com.zerui.manager.icc.dto.DeviceQueryVO;
import com.zerui.manager.icc.properties.ICCProperties;
import com.zerui.manager.web.vo.icc.DeviceInfoVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("iccDeviceInfoService")
public class DeviceInfoService extends AbstractBase {

    // 门禁设备分类
    public final static Integer ACCESS_CONTROL_CATEGORY = 8;

    @Resource
    private ICCProperties iccProperties;

    /**
     * 查询指定条件的所有设备
     *
     * @return
     */
    public List<DeviceInfoVO> getAccessControls() throws ClientException {
        DeviceQueryVO queryVO = new DeviceQueryVO();
        DeviceQueryVO.DeviceExtendCondition deviceExtendCondition = new DeviceQueryVO.DeviceExtendCondition();
        deviceExtendCondition.setCategorys(Collections.singletonList(ACCESS_CONTROL_CATEGORY));
        queryVO.setDeviceExtendConditionList(Collections.singletonList(deviceExtendCondition));
        List<DeviceInfoVO> result = new ArrayList<>();
        int page = 1, totalRows = 0;
        queryVO.setPageSize(100); // 每100条
        queryVO.setMaxRangeId(100000l); // 同步边界值
        do {
            queryVO.setPageNum(page++);
            JSONObject joData = this.generalRequest(iccProperties.getDevice().getListPageUrl(), Method.POST, queryVO, "data");
            totalRows = joData.getIntValue("totalRows");
            JSONArray pageData = joData.getJSONArray("pageData");
            result.addAll(this.convert2TypeData(pageData, DeviceInfoVO.class)); // 保存
        } while ((page - 1) * queryVO.getPageSize() < totalRows);
        return result;
    }

    /**
     * 回去指定设备编号的设备信息
     *
     * @param deviceCode 设备编号
     * @return
     */
    public DeviceInfoVO selectByDeviceCode(String deviceCode) throws ClientException {
        Map<String, String> joParam = new HashMap<>();
        joParam.put("deviceCode", deviceCode);
        JSONObject joData = this.generalRequest(this.renderUrl(iccProperties.getDevice().getDetailUrl(), joParam), Method.GET, null, "data");
        List<DeviceInfoVO> deviceInfoVOS = this.convert2TypeData(joData, DeviceInfoVO.class);
        return !deviceInfoVOS.isEmpty() ? deviceInfoVOS.get(0) : null;
    }

}
